<template>
  <div class="tabLibrary-container">
    <!-- 搜索区域 -->
    <div class="tabLibrary-search">
      <el-button
        size="small"
        type="primary"
        @click="showAddTabDialog"
      ><i class="el-icon-plus" />&nbsp;新增</el-button>
      <span style="padding: 0 10px">标签名称：</span>
      <!-- 绑定-刷新-重置 -->
      <el-input
        v-model="queryInfo.labelName"
        style="width: 200px"
        size="small"
        placeholder="请输入标签名称"
        clearable
        @keyup.enter.native="getTabList"
        @clear="getTabList"
      >
        <el-button
          slot="append"
          size="small"
          icon="el-icon-search"
          @click="getTabList()"
        />
      </el-input>
    </div>

    <!-- 列表区域 -->
    <div>
      <!-- 标签数据 -->
      <el-table
        :data="tabList"
        :header-cell-style="rowClass"
        style="width: 100%"
      >
        <!-- 标签名称，知识类别，标签颜色，排序，备注，创建人，创建时间 -->
        <el-table-column prop="labelName" align="center" label="标签名称" />
        <el-table-column prop="knowCateName" align="center" label="知识类别" />
        <el-table-column prop="labelColor" align="center" label="标签颜色">
          <template slot-scope="scope">
            <span>{{ scope.row.labelColor }}</span>
            <span
              :style="{ color: scope.row.labelColor }"
            ><i class="el-icon-s-flag" />
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="labelSort" label="排序" /> -->
        <el-table-column prop="notes" align="center" label="备注" />
        <el-table-column prop="staffCode" align="center" label="创建人" />
        <el-table-column prop="createtime" align="center" label="创建时间" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              plain
              icon="el-icon-edit"
              @click="showEditTabDialog(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              plain
              icon="el-icon-delete"
              @click="removeTabByID(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页功能 -->
      <div style="padding-top: 10px">
        <el-pagination
          :current-page="queryInfo.pageNum"
          :page-sizes="[5, 10, 20]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 新增标签的对话框 -->
      <el-dialog
        title="新增标签"
        :visible.sync="addTabDialogVisible"
        width="30%"
      >
        <el-form
          ref="addTabForm"
          :model="addTabForm"
          :rules="addTabFormRules"
          label-width="auto"
        >
          <el-form-item label="知识类别" prop="knowCateId">
            <el-select
              v-model="addTabForm.knowCateId"
              placeholder="请选择"
              filterable
            >
              <el-option
                v-for="item in knowCateForm"
                :key="item.knowCateId"
                :label="`${item.cateId}_${item.knowCateName}`"
                :value="item.knowCateId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="标签名" prop="labelName">
            <el-input v-model="addTabForm.labelName" clearable />
          </el-form-item>
          <!-- <el-form-item label="排序" prop="labelSort">
            <el-input v-model="addTabForm.labelSort" clearable />
          </el-form-item> -->
          <el-form-item label="标签颜色" prop="labelColor">
            <el-color-picker v-model="addTabForm.labelColor" />
          </el-form-item>
          <el-form-item label="备注" prop="notes">
            <el-input v-model="addTabForm.notes" clearable />
          </el-form-item>

          <!-- 创建人是否直接引入用户名 -->
          <!-- <el-form-item label="创建人" prop="staffCode">
            <el-input v-model="addTabForm.staffCode" :readonly="true" />
          </el-form-item> -->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addTabDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addTab">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑标签的对话框 -->
      <el-dialog
        title="编辑标签"
        :visible.sync="editTabDialogVisible"
        width="30%"
      >
        <el-form
          ref="editTabForm"
          :model="editTabForm"
          :rules="addTabFormRules"
          label-width="auto"
        >
          <el-form-item label="知识类别">
            <el-select
              v-model="editTabForm.knowCateId"
              placeholder="请选择"
              filterable
              disabled
            >
              <el-option
                v-for="item in knowCateForm"
                :key="item.knowCateId"
                :label="`${item.cateId}_${item.knowCateName}`"
                :value="item.knowCateId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="标签名" prop="labelName">
            <el-input v-model="editTabForm.labelName" clearable />
          </el-form-item>
          <!-- <el-form-item label="排序" prop="labelSort">
            <el-input v-model="editTabForm.labelSort" clearable />
          </el-form-item> -->
          <el-form-item label="标签颜色" prop="labelColor">
            <el-color-picker v-model="editTabForm.labelColor" />
          </el-form-item>
          <el-form-item label="备注" prop="notes">
            <el-input v-model="editTabForm.notes" clearable />
          </el-form-item>

          <!-- 创建人是否直接引入用户名 -->
          <!-- <el-form-item label="创建人" prop="staffCode">
            <el-input v-model="editTabForm.staffCode" :readonly="true" />
          </el-form-item> -->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editTabDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editTab">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getAllLableApi, getKnowCategoryApi, tabInsertApi, tabUpdateApi, tabDeleteByIDApi } from '@/api/knowMan'

export default {
  data() {
    return {
      tabList: [],
      // 查询条件
      queryInfo: {
        pageNum: 1, // 页码
        pageSize: 10 // 每页显示多少条数据
      },
      total: 0,

      // 调用接口数据
      knowCateForm: [],

      // todo 新增标签
      addTabDialogVisible: false,
      addTabForm: {
        knowCateId: '',
        labelName: '',
        // labelSort: '',
        labelColor: '',
        notes: ''
      },
      addTabFormRules: {
        knowCateId: [
          { required: true, message: '请选择知识类别', trigger: 'change' }
        ],
        labelName: [
          { required: true, message: '请输入标签名', trigger: 'blur' }
        ],
        // labelSort: [
        //   { required: true, message: '请输入标签序号', trigger: 'blur' }
        // ],
        labelColor: [
          { required: true, message: '请输入标签颜色', trigger: 'blur' }
        ]
      },

      // todo 编辑标签
      editTabDialogVisible: false,
      editTabForm: {},

      staffCode: ''
    }
  },
  created() {
    this.userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
    this.staffCode = this.userInfo.username ? this.userInfo.username : this.userInfo.staffCode
    this.getTabList()
    this.getKnowCategory()
  },
  methods: {
    // 设置表头的颜色
    rowClass({ row, rowIndex }) {
      return 'background:#f5f7fd'
    },
    // 标签查询
    async getTabList() {
      getAllLableApi(this.queryInfo).then((res) => {
        if (res.code === 200) {
          this.tabList = res.list.records
          this.total = res.list.total
        }
      })
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getTabList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getTabList()
    },

    // todo 新增标签
    getKnowCategory() {
      getKnowCategoryApi().then((res) => {
        if (res.code === 200) {
          this.knowCateForm = res.list
        }
      })
    },
    showAddTabDialog() {
      this.addTabDialogVisible = true
      // ! 创建者暂时设置一个默认值，后续和用户模块绑定
      this.addTabForm.staffCode = this.staffCode
      if (this.$refs.addTabForm !== undefined) {
        this.$refs.addTabForm.resetFields()
        this.addTabForm.knowCateId = ''
      }
    },
    addTab() {
      this.$refs.addTabForm.validate(async(valid, field) => {
        if (!valid) {
          const arr = Object.keys(field)
          return this.$message.error({
            message: field[arr[0]][0].message,
            druation: 1500
          })
        }

        tabInsertApi(this.addTabForm).then((res) => {
          if (res.code === 200) {
            this.addTabDialogVisible = false
            this.getTabList()
          }
        })
      })
    },

    // todo 编辑分类
    async showEditTabDialog(cateInfo) {
      // 用JSON进行深拷贝，防止未请求就修改数据
      this.editTabForm = JSON.parse(JSON.stringify(cateInfo))
      this.editTabDialogVisible = true
      if (this.$refs.editTabForm !== undefined) {
        this.$refs.editTabForm.resetFields()
      }
    },

    async editTab() {
      this.$refs.editTabForm.validate(async(valid, field) => {
        if (!valid) {
          const arr = Object.keys(field)
          return this.$message.error({
            message: field[arr[0]][0].message,
            druation: 1500
          })
        }
        const param = {
          labelCateId: this.editTabForm.labelCateId,
          labelName: this.editTabForm.labelName,
          // labelSort: this.editTabForm.labelSort,
          labelColor: this.editTabForm.labelColor,
          notes: this.editTabForm.notes
        }

        tabUpdateApi(param).then((res) => {
          if (res.code === 200) {
            this.editTabDialogVisible = false
            this.getTabList()
          }
        })
      })
    },

    // todo 删除分类
    async removeTabByID(cateInfo) {
      const result = await this.$confirm(`确定要删除该条记录？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }).catch(reason => reason)

      // 取消删除
      if (result === 'cancel') {
        return this.$message.info({
          message: '已取消删除!',
          druation: 1500
        })
      }
      try {
        tabDeleteByIDApi({
          labelCateId: cateInfo.labelCateId
        }).then((res) => {
          if (res.code === 200) {
            this.$message.success({
              message: '删除成功!',
              druation: 1000
            })
            this.getTabList()
          }
        })
      } catch (error) {
        if (error.response.data.code === 100) {
          return this.$message.error({
            message: error.response.data.tip,
            druation: 1500
          })
        }
      }
    }
  }
}
</script>

<style scoped>
.tabLibrary-container {
  padding: 15px;
}

.el-header {
  padding: 0 40px;
  background-color: #fff;
}
.tabLibrary-search {
  display: flex;
  align-items: center;
  height: 60px;
}

.el-input {
  width: 300px;
}

.el-main {
  overflow: hidden !important;
  margin-top: 15px;
  background-color: #fff;
}
.el-button--mini {
  padding: 7px 3px;
  font-size: 10px;
}

.el-form {
  padding: 0 10px;
}
.el-select,
.el-input {
  width: 80%;
}
div /deep/ .el-dialog {
  margin-top: 40px !important;
  border-radius: 8px;
}
div /deep/ .el-dialog__body {
  padding: 0 25px;
}
</style>
